package com.ilop.permission;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.ilop.permission.adapter.SimpleDataBindingAdapter;
import com.ilop.permission.databinding.ItemPermissionBinding;

import java.util.ArrayList;
import java.util.List;

/**
 * @author skygge
 * @date 6/16/22.
 * GitHub：javofxu@github.com
 * email：skygge@yeah.net
 * description：
 */
public class PermissionAdapter extends SimpleDataBindingAdapter<PermissionEnum, ItemPermissionBinding> {

    private final OnItemClickListener<PermissionEnum> mListener;

    private final List<PermissionEnum> mNotAllowList;

    public void refreshPermission() {
        mNotAllowList.clear();
        notifyDataSetChanged();
    }

    public List<PermissionEnum> getNotAllowList() {
        return mNotAllowList;
    }

    public PermissionAdapter(Context context, OnItemClickListener<PermissionEnum> listener) {
        super(context, R.layout.item_permission, new DiffUtil.ItemCallback<>() {
            @Override
            public boolean areItemsTheSame(@NonNull PermissionEnum oldItem, @NonNull PermissionEnum newItem) {
                return true;
            }

            @Override
            public boolean areContentsTheSame(@NonNull PermissionEnum oldItem, @NonNull PermissionEnum newItem) {
                return true;
            }
        });
        mNotAllowList = new ArrayList<>();
        mListener = listener;
    }

    @Override
    protected void onBindItem(ItemPermissionBinding binding, PermissionEnum item, RecyclerView.ViewHolder holder) {
        binding.setData(item);
        boolean isEnable = getPermissionState(item);
        binding.itemPermissionIcon.setImageResource(item.getIconRes());
        binding.itemPermissionTitle.setText(mContext.getString(item.getTitleRes()));
        binding.itemPermissionMessage.setText(mContext.getString(item.getMessageRes()));
        binding.itemPermissionRight.setImageResource(isEnable ? R.mipmap.icon_select : R.mipmap.icon_go_to);
        if (!isEnable) {
            setOnItemClickListener(mListener);
            mNotAllowList.add(item);
        }
    }

    private boolean getPermissionState(PermissionEnum permission) {
        switch (permission) {
            case PERMISSION_LOCATION:
                return PermissionUtil.onGetLocationPermission(mContext);
            case PERMISSION_CAMERA:
                return PermissionUtil.onGetCameraPermission(mContext);
            case PERMISSION_PUSH:
                return PermissionUtil.isNotificationEnabled(mContext);
        }
        return false;
    }
}
